package cn.jfast.plugin.wizards;

import java.io.IOException;
import java.sql.SQLException;

import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import cn.jfast.plugin.db.MsSql;
import cn.jfast.plugin.db.MySql;
import cn.jfast.plugin.db.OracleSql;
import cn.jfast.plugin.util.StringUtils;
import cn.jfast.plugin.wizards.provider.CellModifyer;
import cn.jfast.plugin.wizards.provider.ContentProvider;
import cn.jfast.plugin.wizards.provider.TableLabelProvider;

public class DataSourcePage extends WizardPage {

	private ISelection selection;
	private Text username;
	private Text pwd;
	private Combo combo;
	private Text host;
	private Text port;
	private Table table;
	private String dburl;
	private Text dbname;
	private String target;

	/**
	 * Create the wizard.
	 */
	public DataSourcePage() {
		super("数据库配置");
		setTitle("数据库配置页");
		setDescription("设置数库连接，输入用户名，密码，连接串,数据库类型");
	}

	/**
	 * @wbp.parser.constructor
	 */
	public DataSourcePage(ISelection selection) {
		super("数据库配置");
		setDescription("设置数库连接，输入用户名，密码，连接串,数据库类型");
		setTitle("数据源设置");
		this.target = "";
		this.selection = selection;
	}

	/**
	 * Create contents of the wizard.
	 * @param parent
	 */
	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		Group dsgroup = new Group(container, SWT.NONE);
		dsgroup.setBounds(0, 0, 432, 75);
		dsgroup.setText("数据源设置");
		// 数据库连接相关设置
		Label label = new Label(dsgroup, SWT.NONE);
		label.setBounds(10, 20, 32, 23);
		label.setText("用户:");

		username = new Text(dsgroup, SWT.BORDER);
		username.setBounds(42, 20, 60, 20);

		Label label_1 = new Label(dsgroup, SWT.NONE);
		label_1.setBounds(106, 20, 32, 23);
		label_1.setText("密码:");

		pwd = new Text(dsgroup, SWT.BORDER | SWT.PASSWORD);
		pwd.setBounds(138, 20, 60, 20);

		Label label_2 = new Label(dsgroup, SWT.NONE);
		label_2.setBounds(10, 45, 32, 23);
		label_2.setText("主机:");

		host = new Text(dsgroup, SWT.BORDER);
		host.setBounds(42, 46, 60, 20);

		Label label_3 = new Label(dsgroup, SWT.NONE);
		label_3.setBounds(106, 49, 32, 23);
		label_3.setText("端口:");

		port = new Text(dsgroup, SWT.BORDER);
		port.setBounds(138, 46, 60, 20);

		Label label_4 = new Label(dsgroup, SWT.NONE);
		label_4.setBounds(202, 20, 39, 20);
		label_4.setText("类型:");

		combo = new Combo(dsgroup, SWT.NONE);
		combo.setItems(new String[] { "MYSQL", "ORACLE","MSSQL" });
		combo.setBounds(243, 17, 70, 22);

		Label lblNewLabel = new Label(dsgroup, SWT.NONE);
		lblNewLabel.setBounds(202, 46, 40, 23);
		lblNewLabel.setText("数据库:");

		dbname = new Text(dsgroup, SWT.BORDER);
		dbname.setBounds(243, 46, 60, 20);
		loadData();

		// 表格显示，用于显示数据源连接成功后查询出来的所有表跟视图
		Group tbcomposite = new Group(container, SWT.NONE);
		tbcomposite.setBounds(0, 80, 432, 243);
		tbcomposite.setText("数据库表");
		final TableViewer tableViewer = new TableViewer(tbcomposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL);
		table = tableViewer.getTable();
		table.setBounds(10, 24, 412, 209);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		TableViewerColumn tableNameViewColumn = new TableViewerColumn(tableViewer, SWT.CENTER);
		TableColumn tableNameColumn = tableNameViewColumn.getColumn();
		tableNameColumn.setWidth(123);
		tableNameColumn.setText("表名");
		TableViewerColumn classNameViewColumn = new TableViewerColumn(tableViewer, SWT.CENTER);
		TableColumn classNameColumn = classNameViewColumn.getColumn();
		classNameColumn.setWidth(122);
		classNameColumn.setText("类名");
		TableViewerColumn remarkViewColumn = new TableViewerColumn(tableViewer, SWT.CENTER);
		TableColumn remarkColumn = remarkViewColumn.getColumn();
		remarkColumn.setWidth(123);
		remarkColumn.setText("注释");
		tableViewer.setColumnProperties(new String[] { "tableName", "nickName", "remark" });
		tableViewer.setLabelProvider(new TableLabelProvider());
		tableViewer.setContentProvider(new ContentProvider());
		CellEditor[] ced = new CellEditor[3];
		ced[0] = null;
		ced[1] = new TextCellEditor(table);
		ced[2] = null;
		tableViewer.setCellEditors(ced);
		tableViewer.setCellModifier(new CellModifyer(tableViewer));
		if (target.length() == 0) {
			setMessage("配置要生成代码的数据库信息!");
		}
		setPageComplete(false);
		setControl(container);
		Button button = new Button(dsgroup, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				table.clearAll();
				loadTable(tableViewer);
				if(table.getColumnCount() > 0)
					setPageComplete(true);
				else 
					setPageComplete(false);
			}
		});
		button.setBounds(360, 35, 46, 27);
		button.setText("连接");
	}

	private void loadTable(TableViewer tableView) {
		String dbuser = getUsername().getText();
		String dbpwd = getPwd().getText();
		String dbtype = getCombo().getText();
		String database = getDbname().getText();
		String dbhost = getHost().getText();
		String dbport = getPort().getText();
		if (StringUtils.isEmpty(dbuser) || StringUtils.isEmpty(dbpwd) || StringUtils.isEmpty(dbtype) || StringUtils.isEmpty(database)
				|| StringUtils.isEmpty(dbhost) || StringUtils.isEmpty(dbport)) {
			MessageDialog.openInformation(getShell(), "数据源", "数据源相关属性不能为空");
			return;
		}
		if(dbtype.equals("MYSQL")){
			dburl = "jdbc:mysql://" + dbhost + ":" + dbport + "/" + database;
			try {
				MySql.instance().initData(dburl, dbuser, dbpwd);
			} catch (SQLException e) {
				e.printStackTrace();
				MessageDialog.openInformation(getShell(), "数据异常", e.getMessage());
				tableView.setInput(null);
				return;
			}
			table.removeAll();
			tableView.setInput(MySql.instance().getTables().toArray(new cn.jfast.plugin.db.Table[]{}));
		} else if(dbtype.equals("ORACLE")){
			dburl = "jdbc:oracle:thin:@"+dbhost+":"+dbport+":"+database;
			try {
				OracleSql.instance().initData(dburl, dbuser, dbpwd);
			} catch (SQLException e) {
				e.printStackTrace();
				MessageDialog.openInformation(getShell(), "数据异常", e.getMessage());
				tableView.setInput(null);
				return;
			}
			table.removeAll();
			tableView.setInput(OracleSql.instance().getTables().toArray(new cn.jfast.plugin.db.Table[]{}));
		}else if(dbtype.equals("MSSQL")){
			dburl = "jdbc:sqlserver://"+dbhost+":"+dbport+"; DatabaseName="+database;
			try {
				MsSql.instance().initData(dburl, dbuser, dbpwd);
			} catch (SQLException e) {
				e.printStackTrace();
				MessageDialog.openInformation(getShell(), "数据异常", e.getMessage());
				tableView.setInput(null);
				return;
			}
			table.removeAll();
			tableView.setInput(MsSql.instance().getTables().toArray(new cn.jfast.plugin.db.Table[]{}));
		}
		saveData(dbuser, dbpwd, dbtype, database, dbhost, dbport, dburl);
		
	}

	private void saveData(String dbuser, String dbpwd, String dbtype, String database, String dbhost, String dbport,
			String url) {
		IDialogSettings dset = getSetting();
		if (dset == null)
			return;
		dset.put("dbuser", dbuser);
		dset.put("dbpwd", dbpwd);
		dset.put("dbtype", dbtype);
		dset.put("database", database);
		dset.put("dbhost", dbhost);
		dset.put("dbport", dbport);
		dset.put("url", dburl);
		saveDs(dset);
	}

	private void saveDs(IDialogSettings dset) {
		try {
			dset.save("jfast.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void loadData() {
		IDialogSettings dset = getSetting();
		try {
			if (dset == null)
				return;
			dset.load("jfast.xml");
			String user = dset.get("dbuser");
			if (null != user) {
				username.setText(user);
			}
			String dbpwd = dset.get("dbpwd");
			if (null != dbpwd)
				pwd.setText(dbpwd);
			String dbtype = dset.get("dbtype");
			if (null != dbtype)
				combo.setText(dbtype);
			String database = dset.get("database");
			if (null != database)
				dbname.setText(database);
			String dbhost = dset.get("dbhost");
			if (null != dbhost)
				host.setText(dbhost);
			String dbport = dset.get("dbport");
			if (null != dbport)
				port.setText(dbport);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
	}

	private IDialogSettings getSetting() {
		return getWizard().getDialogSettings();
	}

	public String getSelectTable() {
		String tb = null;
		int index = table.getSelectionIndex();
		TableItem it = table.getItem(index);
		if (it.getChecked())
			tb = it.getText(0);
		return tb;
	}

	public ISelection getSelection() {
		return selection;
	}

	public void setSelection(ISelection selection) {
		this.selection = selection;
	}

	public Text getUsername() {
		return username;
	}

	public void setUsername(Text username) {
		this.username = username;
	}

	public Text getPwd() {
		return pwd;
	}

	public void setPwd(Text pwd) {
		this.pwd = pwd;
	}

	public Text getHost() {
		return host;
	}

	public void setHost(Text host) {
		this.host = host;
	}

	public Text getPort() {
		return port;
	}

	public void setPort(Text port) {
		this.port = port;
	}

	public Table getTable() {
		return table;
	}

	public void setTable(Table table) {
		this.table = table;
	}

	public String getDburl() {
		return dburl;
	}

	public void setDburl(String dburl) {
		this.dburl = dburl;
	}

	public Combo getCombo() {
		return combo;
	}

	public void setCombo(Combo combo) {
		this.combo = combo;
	}

	public Text getDbname() {
		return dbname;
	}

	public void setDbname(Text dbname) {
		this.dbname = dbname;
	}

}
